<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    
    <title>设计模式之-里氏替换原则LSP | IT浮云</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="通俗的定义：子类可以扩展父类的功能，但不能改变父类原有的功能">
<meta name="keywords" content="lsp,里氏替换">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式之-里氏替换原则LSP">
<meta property="og:url" content="http://www.itfuyun.com/posts/design-pattern-lsp.html">
<meta property="og:site_name" content="IT浮云">
<meta property="og:description" content="通俗的定义：子类可以扩展父类的功能，但不能改变父类原有的功能">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2017-10-20T12:55:23.135Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="设计模式之-里氏替换原则LSP">
<meta name="twitter:description" content="通俗的定义：子类可以扩展父类的功能，但不能改变父类原有的功能">
    

    
        <link rel="alternate" href="/atom.xml" title="IT浮云" type="application/atom+xml" />
    

    
        <link rel="icon" href="/favicon.ico" />
    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">IT浮云</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">文章</a>
                
                    <a class="main-nav-link" href="/about">关于</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/head.jpg" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/.">首页</a></td>
                
                    <td><a class="main-nav-link" href="/archives">文章</a></td>
                
                    <td><a class="main-nav-link" href="/about">关于</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/head.jpg" />
            <h2 id="name">IT浮云</h2>
            <h3 id="title">非典型程序员</h3>
            <span id="location"><i class="fa fa-map-marker"></i>深圳, 中国</span>
            <a id="follow" target="_blank" href="https://github.com/itfuyun/">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                6
                <span>文章</span>
            </div>
            <div class="article-info-block">
                7
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/itfuyun/" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="mailto:itfuyun@gmail.com" target="_blank" title="envelope" class=tooltip>
                            <i class="fa fa-envelope"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="weibo" class=tooltip>
                            <i class="fa fa-weibo"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/atom.xml" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="post-design-pattern-lsp" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            设计模式之-里氏替换原则LSP
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/posts/design-pattern-lsp.html">
            <time datetime="2017-10-20T05:50:53.000Z" itemprop="datePublished">2017-10-20</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/design-pattern/">设计模式</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/lsp/">lsp</a>, <a class="tag-link" href="/tags/里氏替换/">里氏替换</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>通俗的定义：子类可以扩展父类的功能，但不能改变父类原有的功能<br><a id="more"></a></p>
<h4 id="子类可以实现父类的抽象方法，但是不能覆盖父类的非抽象方法。"><a href="#子类可以实现父类的抽象方法，但是不能覆盖父类的非抽象方法。" class="headerlink" title="子类可以实现父类的抽象方法，但是不能覆盖父类的非抽象方法。"></a>子类可以实现父类的抽象方法，但是不能覆盖父类的非抽象方法。</h4><p>为什么这么说呢？先看看违背的话会出现什么情况： </p>
<p>新建一个父类Father，里面一个doSomething（int a，int b）方法</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">doSomething</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> a + b;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>新建一个子类Son继承Father类，里面同样写一个doSomething（int a，int b）方法，这里我们将父类方法进行重写</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">doSomething</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> a * b;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>新建一个Client类，用来测试代码</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> main(<span class="keyword">String</span>[] args) &#123;</div><div class="line">    Son son = <span class="keyword">new</span> Son();</div><div class="line">    System.out.<span class="built_in">println</span>(son.doSomething(<span class="number">3</span>,<span class="number">1</span>));</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以看到控制台打出‘3’，因为执行的是子类的方法，他重写了父类的doSomething方法，也许你系统正好要使用的就是a-b的功能，而你却输出了a乘b的功能，这样对系统造成潜在风险，如果一定要有a*b整个功能，可以看下面一条，直接子类中增加自己特有的方法即可。</p>
<h4 id="子类中可以增加自己特有的方法。"><a href="#子类中可以增加自己特有的方法。" class="headerlink" title="子类中可以增加自己特有的方法。"></a>子类中可以增加自己特有的方法。</h4><p>这个就不需要再说明了</p>
<h4 id="当子类覆盖或实现父类的方法时，方法的前置条件（即方法的形参）要比父类方法的输入参数更宽松。"><a href="#当子类覆盖或实现父类的方法时，方法的前置条件（即方法的形参）要比父类方法的输入参数更宽松。" class="headerlink" title="当子类覆盖或实现父类的方法时，方法的前置条件（即方法的形参）要比父类方法的输入参数更宽松。"></a>当子类覆盖或实现父类的方法时，方法的前置条件（即方法的形参）要比父类方法的输入参数更宽松。</h4><p>这里同样用代码说明，如果违背会怎么样：</p>
<p>新建一个父类Father，里面一个doSomething（Map m）方法</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span>(<span class="params">Map m</span>) </span>&#123;</div><div class="line">    System.<span class="keyword">out</span>.println(<span class="string">"父类方法"</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>新建一个子类Son继承Father类，里面同样写一个doSomething（HashMap m）方法，注意这里可不是重写哦，它们参数不一样，所以为重载</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">doSomething</span>(<span class="params">HashMap m</span>) </span>&#123;</div><div class="line">       System.<span class="keyword">out</span>.println(<span class="string">"子类方法"</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>新建一个Client类，用来测试代码</p>
<figure class="highlight haxe"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> void main(<span class="keyword">String</span>[] args) &#123;</div><div class="line">    Son son = <span class="keyword">new</span> <span class="type">Son</span>();</div><div class="line">    son.doSomething(<span class="keyword">new</span> <span class="type">HashMap</span>());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以看到控制台打出‘子类方法’，这里会出现很大问题，问题在于子类并没有去重写父类的doSomething方法，但是却调用的是子类这个方法，因此同样会对于系统造成潜在风险</p>
<h4 id="当子类的方法实现父类的抽象方法时，方法的后置条件（即方法的返回值）要比父类更严格。"><a href="#当子类的方法实现父类的抽象方法时，方法的后置条件（即方法的返回值）要比父类更严格。" class="headerlink" title="当子类的方法实现父类的抽象方法时，方法的后置条件（即方法的返回值）要比父类更严格。"></a>当子类的方法实现父类的抽象方法时，方法的后置条件（即方法的返回值）要比父类更严格。</h4><p>这里也不需要过多说了，子类的返回类型必须小于或等于父类抽象方法的返回类型</p>

        
        </div>
		
		
            
<div>
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div style="margin-bottom:10px">请作者喝杯咖啡吧！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
        <div id="wechat" style="display: inline-block">
          <a href="/css/images/wechatpay.png" class="fancybox fancybox.image" rel="group"><img id="wechat_qr" src="/css/images/wechatpay.png" alt="过眼浮云 WeChat Pay"></a>
          <p>微信打赏</p>
        </div>
        <div id="alipay" style="display: inline-block">
          <a href="/css/images/alipay.png" class="fancybox fancybox.image" rel="group"><img id="alipay_qr" src="/css/images/alipay.png" alt="过眼浮云 Alipay"></a>
          <p>支付宝打赏</p>
        </div>
    </div>
  </div>
</div>

        
		
		
            <! -- 添加版权信息 -->
<div class="article-footer-copyright">
<div>本站文章除注明转载外，均为本站原创或编译。欢迎任何形式的转载，但请务必注明出处。</div>
<div>转载请注明：文章转载自 IT浮云 <a href="/index.html" target="_blank" title="IT浮云">[http://www.itfuyun.com]</a></div>
<div>本文标题：设计模式之-里氏替换原则LSP</div>
<div>本文地址：<a href="/posts/design-pattern-lsp.html" target="_blank" title="设计模式之-里氏替换原则LSP">http://www.itfuyun.com/posts/design-pattern-lsp.html</a></div>
</div>
<! -- 添加版权信息 -->
        
		
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    
        <a href="http://www.itfuyun.com/posts/design-pattern-lsp.html#comments" id="sourceId::posts/design-pattern-lsp.html" class="article-comment-link cy_cmt_count">评论</a>
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
    
        <a href="/posts/freemarker-generates-static-files.html" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">Freemarker生成静态文件</div>
        </a>
    
</nav>


    
</article>


    
    
        <section id="comments">
    <div id="SOHUCS" sid="posts/design-pattern-lsp.html"></div>
</section>
    

</section>
            
                
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="no-thumbnail">
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/design-pattern/">设计模式</a></p>
                            <p class="item-title"><a href="/posts/design-pattern-lsp.html" class="title">设计模式之-里氏替换原则LSP</a></p>
                            <p class="item-date"><time datetime="2017-10-20T05:50:53.000Z" itemprop="datePublished">2017-10-20</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/programming/">编程</a></p>
                            <p class="item-title"><a href="/posts/freemarker-generates-static-files.html" class="title">Freemarker生成静态文件</a></p>
                            <p class="item-date"><time datetime="2017-10-16T07:58:51.000Z" itemprop="datePublished">2017-10-16</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/source-code-analysis/">源码分析</a></p>
                            <p class="item-title"><a href="/posts/hashmap-source-code-analysis.html" class="title">HashMap 源码分析</a></p>
                            <p class="item-date"><time datetime="2017-10-14T06:31:55.000Z" itemprop="datePublished">2017-10-14</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/programming/">编程</a></p>
                            <p class="item-title"><a href="/posts/java-cookie-utils.html" class="title">Java操作Cookie工具类</a></p>
                            <p class="item-date"><time datetime="2017-09-27T14:53:34.000Z" itemprop="datePublished">2017-09-27</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/programming/">编程</a></p>
                            <p class="item-title"><a href="/posts/rapid-generator.html" class="title">告别枯燥的CRUD，Java代码生成器的使用</a></p>
                            <p class="item-date"><time datetime="2017-09-26T12:49:39.000Z" itemprop="datePublished">2017-09-26</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/other/">其他</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/source-code-analysis/">源码分析</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/programming/">编程</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/design-pattern/">设计模式</a><span class="category-list-count">1</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">归档</h3>
        <div class="widget">
            <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/10/">十月 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/09/">九月 2017</a><span class="archive-list-count">3</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签云</h3>
        <div class="widget tagcloud">
            <a href="/tags/cookie/" style="font-size: 10px;">-cookie</a> <a href="/tags/hexo/" style="font-size: 10px;">-hexo</a> <a href="/tags/代码生成/" style="font-size: 10px;">-代码生成</a> <a href="/tags/HashMap/" style="font-size: 10px;">HashMap</a> <a href="/tags/freemarker/" style="font-size: 10px;">freemarker</a> <a href="/tags/lsp/" style="font-size: 10px;">lsp</a> <a href="/tags/里氏替换/" style="font-size: 10px;">里氏替换</a>
        </div>
    </div>

    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

            
        </div>
        <footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy; 2018 IT浮云<br>
            Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>. Theme by <a href="http://github.com/ppoffice">PPOffice</a>
        </div>
    </div>
</footer>
        
    
    <script id="cy_cmt_num" src="https://changyan.sohu.com/upload/plugins/plugins.list.count.js?clientId=cytezlr4l"></script>
    <script charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/changyan.js" ></script>
    <script type="text/javascript">
    window.changyan.api.config({
    appid: 'cytezlr4l',
    conf: '7625b051042273ad10802550abd3d130'
    });
    </script>




    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>